package conceptmaniax.hotelapp.activities;

import java.io.File;
import java.text.ParseException;

import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TextView;
import conceptmaniax.hotelapp.adapters.PhotoFragment;
import conceptmaniax.hotelapp.config.Constants;
import conceptmaniax.hotelapp.enums.Language;
import conceptmaniax.hotelapp.managers.RequestManager;
import conceptmaniax.hotelapp.util.GeneralUtils;
import conceptmaniax.hotelapp.util.database.DataHelper;

public class DetailItemActivity extends FragmentActivity {
		
	private DataHelper dataHelper = new DataHelper(this, Constants.DATABASE_NAME);
	private Language language;
	private String action;
	
	protected Button showInfo;
	protected Button showServices;
	protected Button showGuide;
	protected Button showBooking;
	protected Button requests;
	protected Button more_info;
	protected Button more_info_text;
	protected TableLayout callout;
	protected ListView callout_list;
	protected ViewPager homeScreen;
	protected FrameLayout details;
	protected TextView counter;

	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.hotel_items);
		language = GeneralUtils.getLanguage(this);
		
		//Go back to HomePage Button
		final Button go_to_home = (Button) findViewById(R.id.homeButton);
			go_to_home.setOnClickListener(new View.OnClickListener() {
			public void onClick(final View view) {
		    	final Intent homePageIntent = new Intent(Constants.HOMEPAGE_ACTIVITY);
		    	startActivity(homePageIntent);
			}
		});
			
		// Parse String array from previous intent
		action = getIntent().getExtras().getString("action");
		String open = getIntent().getExtras().getString("contact");
			
		showInfo = (Button) findViewById(R.id.hotel_button);
		showServices = (Button) findViewById(R.id.services_button);
		showGuide = (Button) findViewById(R.id.guide_button);
		showBooking = (Button) findViewById(R.id.booking_button);
		homeScreen = (ViewPager) findViewById(R.id.pager);
		requests = (Button) findViewById(R.id.requestsButton);
		callout = (TableLayout) findViewById(R.id.callout_table);
		callout_list = (ListView) findViewById(R.id.callout_listview);
		more_info = (Button) findViewById(R.id.more_info_button);
		more_info_text = (Button) findViewById(R.id.more_info_text);
		details = (FrameLayout)findViewById(R.id.more_info_container);
		counter = (TextView) findViewById(R.id.counter);

		if (open != null) {
			more_info.setSelected(true);
			more_info_text.setSelected(true);
			more_info.setBackgroundResource(R.drawable.up_arrow);
		    Animation a = AnimationUtils.loadAnimation(getBaseContext(), R.anim.appear_from_top);
		    a.reset();
			details.clearAnimation();
		    details.startAnimation(a);
			details.setVisibility(View.VISIBLE);
			switch(language) {
				case ENGLISH:
					more_info_text.setText("less information");
					break;
				case GREEK:
					more_info_text.setText("λιγότερα");
					break;
			}
		}
			
			more_info.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (!more_info.isSelected() && !more_info_text.isSelected()) {
						more_info.setSelected(true);
						more_info_text.setSelected(true);
						more_info.setBackgroundResource(R.drawable.up_arrow);
					    Animation a = AnimationUtils.loadAnimation(getBaseContext(), R.anim.appear_from_top);
					    a.reset();
					    details.clearAnimation();
					    details.startAnimation(a);
						details.setVisibility(View.VISIBLE);
						switch(language) {
							case ENGLISH:
								more_info_text.setText("less information");
								break;
							case GREEK:
								more_info_text.setText("λιγότερα");
								break;
						}
					} else {
						more_info.setSelected(false);
						more_info_text.setSelected(false);
						more_info.setBackgroundResource(R.drawable.down_arrow);
					    Animation a = AnimationUtils.loadAnimation(getBaseContext(), R.anim.disappear);
					    a.reset();
					    details.clearAnimation();
					    details.startAnimation(a);
						details.setVisibility(View.INVISIBLE);
						homeScreen.setVisibility(View.VISIBLE);
						switch(language) {
						case ENGLISH:
							more_info_text.setText("more information");
							break;
						case GREEK:
							more_info_text.setText("περισσότερα");
							break;
						}
					}
				}
			});
			
			more_info_text.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (!more_info.isSelected() && !more_info_text.isSelected()) {
						more_info.setSelected(true);
						more_info_text.setSelected(true);
						more_info.setBackgroundResource(R.drawable.up_arrow);
					    Animation a = AnimationUtils.loadAnimation(getBaseContext(), R.anim.appear_from_top);
					    a.reset();
					    details.clearAnimation();
					    details.startAnimation(a);
						details.setVisibility(View.VISIBLE);
						switch(language) {
							case ENGLISH:
								more_info_text.setText("less information");
								break;
							case GREEK:
								more_info_text.setText("λιγότερα");
								break;
						}
					} else {
						more_info.setSelected(false);
						more_info_text.setSelected(false);
						more_info.setBackgroundResource(R.drawable.down_arrow);
					    Animation a = AnimationUtils.loadAnimation(getBaseContext(), R.anim.disappear);
					    a.reset();
					    details.clearAnimation();
					    details.startAnimation(a);
						details.setVisibility(View.INVISIBLE);
						switch(language) {
						case ENGLISH:
							more_info_text.setText("more information");
							break;
						case GREEK:
							more_info_text.setText("περισσότερα");
							break;
						}
					}
				}
			});
		
	    homeScreen.setAdapter(new PhotoPagerAdapter(getSupportFragmentManager()));
	}
	
			public class PhotoPagerAdapter extends FragmentPagerAdapter {
		    	int number = getNumberofImages(fillFields(action));
		        public PhotoPagerAdapter(FragmentManager fm) {
		        super(fm);
		    }

		    @Override
		    public Fragment getItem(int position) {
		    	PhotoFragment fragment = new PhotoFragment();
		        // set arguments here, if required
		        Bundle args = new Bundle();
				args.putString("name",fillFields(action));
				args.putInt("position", position+1);
				fragment.setArguments(args);
				
		        return fragment;
		    }
		    
		    @Override
		    public int getCount() {
		    	return number;
		    }
	}
	
	private int getNumberofImages(final String imgName) {
		int i = 0;
    	for (int y=1; y<=Constants.MAX_IMAGES_PER_ITEM; y++) {
			File scrollImageFile = new File(getFilesDir().getAbsolutePath() + File.separator + Constants.IMAGES_FOLDER + File.separator + Constants.IMAGES_FOLDER + File.separator + imgName + "_" +y + ".jpg");
			if (scrollImageFile.exists()) 
				i++;
    	}
    	return i;
	}

	private String fillFields(final String action) {
		String itemQuery = null;
		switch(language) {
		case ENGLISH:
			itemQuery = "SELECT i._id,"
					+ "i.name_en,"
					+ " i.description_en,"
					+ "i.photo FROM item i,"
					+ " menu m, menu_item mi "
					+ "WHERE m._id = mi.menu_id "
					+ "AND i._id = mi.item_id "
					+ "AND m.activity = '"+action+"'";
			break;
		case GREEK:
			itemQuery = "SELECT i._id,"
					+ "i.name_gr,"
					+ " i.description_gr,"
					+ "i.photo FROM item i,"
					+ " menu m, menu_item mi "
					+ "WHERE m._id = mi.menu_id "
					+ "AND i._id = mi.item_id "
					+ "AND m.activity = '"+action+"'";
			break;
		}
		Cursor cursor =	dataHelper.getData(itemQuery);
		cursor.moveToNext();
		String temp = cursor.getString(3);
		final TextView itemType = (TextView)findViewById(R.id.hotel_items_title);
		final TextView detailstxt = (TextView)findViewById(R.id.more_info);
		itemType.setText(cursor.getString(1));
		detailstxt.setText(cursor.getString(2));
        cursor.close();
    	if ( dataHelper != null ) dataHelper.close();
        return temp;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if ( this.dataHelper != null ) this.dataHelper.close();
		unbindDrawables(findViewById(R.id.hotel_items_relative));
	    System.gc();  
	}
	
	private void unbindDrawables(View view) {
        if (view.getBackground() != null) {
        	view.getBackground().setCallback(null);
        }
        if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
            	unbindDrawables(((ViewGroup) view).getChildAt(i));
            }
            ((ViewGroup) view).removeAllViews();
        }
    }
	
	@Override
	protected void onResume() {
		super.onResume();
		switch(language) {
		case ENGLISH:
			more_info_text.setText("more information");
			break;
		case GREEK:
			more_info_text.setText("περισσότερα");
			break;
		}
		SetButtonActivity.getInstance().setRecognition(false);
		SetButtonActivity.getInstance().setButtons(this, showInfo,
				showServices, showGuide, showBooking, callout, callout_list,
				homeScreen, requests);
		try {
			int counter = RequestManager.getInstance().getRequestCount();
			this.counter.setText(""+counter);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    // manage message counter
	    if (this.counter.getText().equals("0")) 
	        this.counter.setVisibility(View.INVISIBLE);
	     else
	        this.counter.setVisibility(View.VISIBLE);
	}
	
	@Override
	public boolean onCreateOptionsMenu(final Menu menu) {		
		return super.onCreateOptionsMenu(GeneralUtils.createOptionsMenu(this, menu));
	}
	
	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {
		GeneralUtils.onOptionsItemSelected(this, item);
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected Dialog onCreateDialog(final int id) {
		return GeneralUtils.createAboutUsDialog(this);
	}
}